//
//  WbRefreshControl.swift
//  Weibo
//
//  Created by HH on 16/12/8.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit

private enum wbRefreshControlType {
    //下拉刷新
    case normal
    //松手就刷新
    case pulling
    //正在刷新
    case refreshing
}

class WbRefreshControl: UIControl {
    
    var currentScrollView:UIScrollView?
    
    //箭头
    lazy private var iconView:UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    
    //风火轮
    lazy private var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    
    //描述信息
    lazy private var descLabel:UILabel = {
       
        let label = UILabel()
        
        label.text = "下拉刷新"
        
        label.font = UIFont.systemFont(ofSize: 12)
        
        label.textColor = UIColor.gray
        
        return label
        
        
    }()
    
    private var refreshType:wbRefreshControlType = .normal{
        
        didSet{
            
            switch refreshType {
            case .normal:
                print("下拉刷新")
                
                iconView.isHidden = false
                indicatorView.stopAnimating()
                
                UIView.animate(withDuration: 0.1, animations: {
                    self.iconView.transform = CGAffineTransform.identity
                })
                
                descLabel.text = "下拉刷新"
                
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.currentScrollView?.contentInset.top -= 50
                    })
                }
                
            case .pulling:
                //松手就刷新
                
                print("松手就刷新")
                
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    self.iconView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                
                descLabel.text = "松手就刷新"
            case .refreshing:
                //正在刷新
                
                print("正在刷新")
                
                iconView.isHidden = true
                indicatorView.startAnimating()
                descLabel.text = "正在刷新"
                
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScrollView?.contentInset.top += 50
                })
                
                //发送事件,让外部开始加载数据
                sendActions(for: .valueChanged)
           
            }
            
            
        }
    }

    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        addSubview(iconView)
        addSubview(indicatorView)
        addSubview(descLabel)
        
        iconView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        descLabel.translatesAutoresizingMaskIntoConstraints = false
        
       addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: iconView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconView, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: descLabel, attribute: .leading, relatedBy: .equal, toItem: iconView, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: descLabel, attribute: .centerY, relatedBy: .equal, toItem: iconView, attribute: .centerY, multiplier: 1, constant: 0))
        
        
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
//        super.willMove(toSuperview: newSuperview)
        
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        self.frame = CGRect(x: 0, y: -50, width: scrollView.width, height: 50)
        
        //KVO
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        currentScrollView = scrollView
        
    }
    
    //监听滚动
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
//         print(currentScrollView?.contentOffset)
        let conoffsetY = currentScrollView!.contentOffset.y
        
        let maxY:CGFloat = -(currentScrollView!.contentInset.top + 50)
        
        if currentScrollView!.isDragging {
            
            if conoffsetY < maxY && refreshType == .normal {
//                print("下拉刷新状态")
                refreshType = .pulling
                
            }else if conoffsetY >= maxY && refreshType == .pulling {
//                print("过了临界点")
                refreshType = .normal
            }
        }else{
//            print("正在刷新")
            if refreshType == .pulling {
                refreshType = .refreshing
            }
        }

    }
    
    
    func endRefresh(){
        
        refreshType = .normal
    }
    
    deinit {
        //移除监听者
        currentScrollView?.removeObserver(self, forKeyPath: "contoffset")
    }

}
